﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xlit.Project.Entity.Domain;
using Xlit.Project.Service;
using Xlit.Standard.Data;

namespace Xlit.Example.Business.Services
{
    /// <summary>
    ///  菜单管理
    /// </summary>
    public class SysMenuService : AppServiceBase
    {
        public IRepository<Sys_Menu, int> SysMenuRepository { get; set; }

        /// <summary>
        ///  获取菜单树
        /// </summary>
        /// <returns></returns>
        public IList<Sys_Menu> Get()
        {
            var list = SysMenuRepository.GetList();
            var menus = list.OrderBy(d => d.Sort).Where(d => !d.ParentId.HasValue);
            return menus.ToList();
        }

        /// <summary>
        ///  获取菜单
        /// </summary>
        /// <param name="id">菜单id</param>
        /// <returns></returns>
        public Sys_Menu Get(int id)
        {
            return SysMenuRepository.GetEntity(id);
        }

        /// <summary>
        ///  更新菜单
        /// </summary>
        /// <param name="input">菜单</param>
        /// <returns></returns>
        public int Update(Sys_Menu input)
        {
            return SysMenuRepository.InsertOrUpdate(input);
        }

        /// <summary>
        ///  删除菜单
        ///  有子菜单的不能删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(int id)
        {
            if (SysMenuRepository.IsExist(d => d.ParentId == id))
                throw new ApplicationException("请先删除子菜单");
            return SysMenuRepository.Delete(id);
        }
    }
}
